﻿# -*- coding: UTF-8 -*-
import logging
import requests
import json
import hashlib
import time
from requests.auth import HTTPBasicAuth

# 配置日志文件路径
log_file_path = "./rabbitmq.log"
# 设置日志记录配置
logging.basicConfig(
    filename=log_file_path,  # 指定日志文件路径
    level=logging.INFO,  # 设置日志级别为INFO
    format="%(asctime)s - %(levelname)s - %(message)s",  # 设置日志格式，包括时间、日志级别和消息
    datefmt="%Y-%m-%d %H:%M:%S",  # 设置时间格式
)


def send_alert(message, phone_number):
    """发送告警短信

    参数:
    message (str): 告警信息
    phone_number (str): 目标手机号码
    """
    # 短信发送接口URL
    url = "http://61.145.229.28:7902/sms/v2/std/send_single"
    # 获取当前时间戳，格式为 MMDDHHMMSS
    timestamp = time.strftime("%m%d%H%M%S", time.localtime())
    uid = "JS9015"  # 用户ID
    pwd = "256310"  # 用户密码

    logging.info("正在处理告警发送...")

    # 生成MD5加密的密码
    tempPwd = f"{uid.upper()}00000000{pwd}{timestamp}"
    md5 = hashlib.md5()
    md5.update(tempPwd.encode("utf-8"))
    md5Pwd = md5.hexdigest()

    # 构建短信内容
    msg = f"RabbitMQ 产生告警：{message}，请关注！"

    # 构建请求数据
    data = {
        "userid": uid,
        "pwd": md5Pwd,
        "mobile": phone_number,
        "timestamp": timestamp,
        "svrtype": "SMS001",
        "content": msg,
    }

    try:
        # 发送POST请求
        response = requests.post(url, data=data)
        response.raise_for_status()  # 如果请求失败，抛出HTTP错误
        result = response.json()  # 将响应内容解析为JSON格式
        logging.info(f"告警发送成功，返回状态：\n{json.dumps(result, indent=2)}")
    except requests.RequestException as e:
        logging.error(f"告警发送失败：{e}")


def get_mq_deliver():
    """获取 RabbitMQ 的 Deliver (manual ack) 速率并发送告警"""
    # RabbitMQ API的URL
    url = "http://10.5.1.48:15672/api/queues"
    username = "cloud"  # API用户名
    password = "7#BD2CFc3TBV}7m7z"  # API密码
    phone_number_list = ["13421830635", "18320811590"]  # 告警接收手机号码列表

    try:
        # 使用HTTP基本认证访问RabbitMQ API
        response = requests.get(url, auth=HTTPBasicAuth(username, password))
        response.raise_for_status()  # 如果请求失败，抛出HTTP错误

        queues = response.json()  # 将响应内容解析为JSON格式
        total_deliver_manual_ack_rate = 0  # 初始化总的手动确认消息传递速率

        # 遍历每个队列，计算手动确认消息传递速率
        for queue in queues:
            message_stats = queue.get("message_stats", {})
            deliver_auto_ack_rate = message_stats.get("deliver_no_ack_details", {}).get(
                "rate", 0
            )
            deliver_rate = message_stats.get("deliver_details", {}).get("rate", 0)
            deliver_manual_ack_rate = deliver_rate - deliver_auto_ack_rate
            total_deliver_manual_ack_rate += deliver_manual_ack_rate

        # 将总的手动确认消息传递速率四舍五入保留一位小数
        total_deliver_manual_ack_rate = round(total_deliver_manual_ack_rate, 1)
        logging.info(f"当前 Deliver (manual ack): {total_deliver_manual_ack_rate}/s")

        # 如果手动确认消息传递速率超过100/s，发送告警
        if total_deliver_manual_ack_rate > 100:
            alert_message = f"Deliver (manual ack): {total_deliver_manual_ack_rate}/s"
            for phone_number in phone_number_list:
                send_alert(alert_message, phone_number)
                time.sleep(5)  # 两次告警之间等待5秒
            logging.info("所有告警信息已发送！\n")
        else:
            logging.info(
                "当前 total_deliver_manual_ack_rate 小于 100，无需发送告警。\n"
            )

    except requests.RequestException as e:
        logging.error(f"数据获取错误：{e}")


if __name__ == "__main__":
    # 主函数，执行获取RabbitMQ速率并检查是否需要发送告警
    get_mq_deliver()
